import config from "./config.js";
import {
	nativeUI,
	saveClosePage
} from '@/utils/index.js'
import local from '@/utils/localStorage.js'; //引入本地存储方法
/* 
		@parms url 接口地址
		@parms method 请求方式
		@parms data 参数
		@parms isUpload 默认false 是否上传
 */

const request = (url, method, data, isUpload = false, name = 'file') => {
	console.log(local.get('token'));
	return new Promise((resolve, reject) => {
		if (!isUpload) {
			uni.request({
				url: config.baseURL + url, //仅为示例，并非真实接口地址。
				data: data,
				method: method,
				timeout:config.timeout,
				header: {
					'Content-Type': 'application/x-www-form-urlencoded',
					// 'Content-Type': 'application/json; charset=utf-8',
					// 'Token': local.get('token') || '', //登录凭证
					'token': local.get('token') || '',
					'UserAuth': 'user'
				},
				success: (res) => { //具体捕获请看自己接口返回的形式
					console.log(res);
					if (res.data.code == 1 || res.data.code == 100 || res.data.code == 2  || res.data.code == 4) {
						resolve(res.data)
					} else if (res.data.code == 401) {
						local.remove('token')
						setTimeout(() => {
							uni.$uv.route({
								type: 'redirect',
								// #ifdef MP-WEIXIN
								url: '/subcontracting/Login/wxlogin/wxlogin', //如果是微信小程序跳转到微信授权页面
								// #endif
								// #ifndef MP-WEIXIN
								url: '/pages/Login/login/login'
								// #endif
							})
							// 保存页面失效当前路径
							// saveClosePage()
						}, 1000)
						nativeUI('登录状态失效')

					} else {
						nativeUI(res.data.msg)
					}
				},
				fail(error) {
					console.error(error);
					reject(error)
				},
			});
		} else {
			console.log(data,name);
			uni.uploadFile({
				url: config.baseURL + url,
				filePath: data,
				name,
				header: {
					// 'Content-Type': 'application/json; charset=utf-8',
					'token': local.get('token') || '',
				},
				success: (uploadFileRes) => {
					let parms = JSON.parse(uploadFileRes.data)
					if (parms.code == 200 || parms.code == 1 || parms.code == 1204) {
						resolve(parms)
					} else {
						// uni.$u.toast()
						nativeUI(parms.info)
					}
				},
				fail: (e) => {
					console.log(e);

					nativeUI('上传失败')
				}
			});
		}

	})
}

export default {
	request //向外暴露request
}